package com.example.manager;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.domain.user.User;
import com.example.domain.user.vo.UserVO;
import com.example.mapper.user.UserMapper;
import com.example.redis.service.RedisService;
import oj.common.core.contants.CacheConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class UserCacheManager {
    @Autowired
    private RedisService redisService;
    @Autowired
    private UserMapper userMapper;
    /**
     * 在查看详细的时候使用
     * @param userId
     * @return
     */
    public UserVO getUserVOById(Long userId) {
        String userKey = getUserCacheKey(userId);
        UserVO userVO = redisService.getCacheObject(userKey, UserVO.class);
        if (userVO != null) {
            //将缓存延长10min
            redisService.expire(userKey, CacheConstants.USER_EXP, TimeUnit.MINUTES);
            return userVO;
        }
        //如果redis中没有的话，就去mysql中查看
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .select(User::getUserId,
                        User::getNickName,
                        User::getHeadImage,
                        User::getSex,
                        User::getEmail,
                        User::getPhone,
                        User::getWechat,
                        User::getIntroduce,
                        User::getSchoolName,
                        User::getMajorName,
                        User::getStatus)
                .eq(User::getUserId, userId));
        if(user==null) {
            return null;
        }
        refreshUser(user);
        userVO = new UserVO();
        BeanUtil.copyProperties(user, userVO);
        return userVO;
    }
    public void refreshUser(User user) {
        String userCacheKey  = getUserCacheKey(user.getUserId());
        redisService.setCacheObject(userCacheKey, user);
        redisService.expire(userCacheKey,CacheConstants.USER_EXP, TimeUnit.MINUTES);

    }

    private String getUserCacheKey(Long userId) {
        return CacheConstants.USER_DETAIL+userId;
    }
}
